<?php
/*
 * Created on May 25, 2009
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
?>
<?php
 
 if ( ! defined('BASEPATH')) exit('No direct script access allowed');
	class Price extends VNT_Controller{
		function Price(){
			parent::VNT_Controller();
			$this->load->library('xajax', 'category');
			$this->xajax->registerFunction(array('test', &$this, 'test')); 
			
			$this->xajax->processRequest();
			$this->xajax_js = $this->xajax->getJavascript($this->base_url.'js/');
			$this->load->model('file_model', 'files', true);
			$this->load->model('pcategory_model', 'pcategory', true);
			$this->checkLogin();
		}
		
		function index(){
			//echo $this->config->item('language');
			//$this->main = '<div> erer erer er </div>';
			//$this->execute();
			//$this->load->view('main', '');
			$this->view();
		}
		
		function create(){
			$obj = new stdClass();
			$obj->id_file = 0;
			$obj->id_category = 0;
			$obj->vi_alias = '';
			$obj->en_alias = '';
			$obj->description = '';
			$obj->file_name = '';
			$obj->active = 1;
			$obj->add_date = date('Y-m-d H:i:s', time());
			$obj->upd_date = date('Y-m-d H:i:s', time());
						
			$obj->code = ''; 
					
			$data = array();
			$data['file'] = $obj;
			$data['ddlCategory'] = $this->buidDDProductCategoryList('category', '');
			$data['error_message'] = '';
			$data['legend_text'] = lang('upload_file');
			$this->main = $this->load->view('admin/file/create_file', $data, true);
			$this->execute();
		}
		
		function edit($id){
			$file = $this->files->getById($id);
			
			if(!$file){
				//redirect('admin/price/view');
				redirect($_SESSION['his_adm']);
				return;
			}
			
			$data = array();
			$data['file'] = $file;
			
			$cat = $this->pcategory->getById($file->id_category); 
			$cat_code = '';
			if($cat) $cat_code = $cat->code;
			
			$data['ddlCategory'] = $this->buidDDProductCategoryList('category', $cat_code);
			$data['error_message'] = '';
			$data['legend_text'] = lang('edit_product_category');
			$this->main = $this->load->view('admin/file/create_file', $data, true);
			$this->execute();
		}
		
		function create_from_file(){ //   
			$error_message = ''; 
			if(isset($_FILES['file']['tmp_name'])){
				$config['upload_path'] = './Data/';
				$config['allowed_types'] = 'xls';
				//$config['overwrite'] = true; 
				$config['max_size']	= 8192; // 8192 kb = 8mb
				//$config['max_width']  = '1024';
				//$config['max_height']  = '768';
				//$config['max_filename'] = 50; 
				//$config['encrypt_name'] = true; 
				//$config['remove_spaces'] = false; 
				$result_upload = $this->uploadFile($config);
				if($result_upload['error']){
						
					$error_message = $result_upload['message']; 
				}
				else{
					
					//if($result_upload['upload_data']['file_type']==)
					//echo $config['upload_path'].$result_upload['upload_data']['file_name'];
					//echo mime_content_type($config['upload_path'].$result_upload['upload_data']['file_name']);
					
					$this->load->library('excel/spreadsheet_Excel_Reader');
							
					$data = new Spreadsheet_Excel_Reader();
			    
					$data->setOutputEncoding('utf-8');
					//$data->setOutputEncoding('windows-1258');
					//$data->setOutputEncoding('iso-8859-1');
				
			   		$data->read($config['upload_path'].$result_upload['upload_data']['file_name']);
					if(!isset($data->_ole->error)){
						//$data->read('BG MBT 1P 4-2009.xls');
						//$data->sheets[1]['cells'][2][3];
						//$data->sheets[SHEET]['cells'][ROW][COLUMN];
				//print_r($data);
						error_reporting(E_ALL ^ E_NOTICE);
						//$colspan = 1;
						//echo "Sheet:".count($data->sheets);
						//echo "Sheet:".$data->sheets[0]['numCols'];
						$objects = array();
						for($a = 0; $a < count($data->sheets); $a++){
							//echo 'TEn sheet:' . $data->boundsheets[$a]['name'];
							for ($i = 2; $i <= $data->sheets[$a]['numRows']; $i++) {
								//if($data->sheets[$a]['numCols'] < 3) break;
								//echo "<br>Row:".$data->sheets[$a]['cellsInfo'][1] .'_'. $i;
								$obj = new stdClass();
								$obj->id_parent_pcategory = 0;
								//$obj->vi_name = '';
								//$obj->en_name = '';
								$obj->vi_description = '';
								$obj->en_description = '';
								$obj->number_product = 0;
								$obj->link_rewrite = '';
								$obj->meta_title = '';
								$obj->meta_keywords = '';
								$obj->meta_description = '';
								$obj->level_depth = 0;
								$obj->active = 1;
								$obj->module = PRODUCTS_PAGE;
								$obj->date_add = date('Y-m-d H:i:s', time());
								$obj->date_upd = date('Y-m-d H:i:s', time());
						
								$obj->code = trim($data->sheets[$a]['cells'][$i][1]); 
								$obj->code_parent = trim($data->sheets[$a]['cells'][$i][2]);
								$obj->vi_name = trim($data->sheets[$a]['cells'][$i][3]); 
								$obj->en_name = trim($data->sheets[$a]['cells'][$i][3]); 
								if($obj->code!='' AND $obj->code!=null AND $obj->vi_name!='' AND $obj->vi_name!=null)
									$objects[] = $obj;
								//	break;
								//if($obj->code!='' AND $obj->vi_name!='')
								//$objects[] = $obj;
								
								/*
								for ($j = 1; $j <= $data->sheets[$a]['numCols']; $j++) {
									$value = $data->sheets[$a]['cells'][$i][$j];
									$colspan = $data->sheets[$a]['cellsInfo'][$i][$j]['colspan'];
									if($colspan){
										//echo "<td colspan='$colspan' style='border-bottom:1px solid black;'>". $value . "</td>\n";
									}
									else{
										if(!$value) $value = "&nbsp;";
										//echo "<td style='border-bottom:1px solid black;'>". $value . "</td>\n";
										$colspan = 1;
									}
								
								} // for column		
								*/		
							
							} //for row
						} // for count sheet
						if(count($objects)>0){
							$result = $this->pcategory->create($objects);
							if($result){
								$this->pcategory->updateParentId();
							}
							@unlink($config['upload_path'].$result_upload['upload_data']['file_name']);
							//redirect('admin/pcategory');	
							//return;
						}
						
					} //if
					else{
						$error_message .= 'The filename ' . $result_upload['upload_data']['file_name'] . ' is not readable';
					}
			
				}
			}
			$data = array();
			$data['error_message'] = '<div style="color:red">'.$error_message . '</div>';
			$this->main = $this->load->view('admin/pcategory/form_upload', $data, true);
			$this->execute();
		}
		
		function upload_file($field_name, $path)
		{
			$result = array();
			$config['upload_path'] = $path; //'./Data/Images/';
			$config['allowed_types'] = 'xls|gif|jpg|png|doc|pdf|txt';
			//$config['max_size']	= '1000';
			//$config['max_width']  = '1024';
			//$config['max_height']  = '768';
			$config['overwrite']  = false;
			
			
			$this->load->library('upload', $config);
		
			if (!$this->upload->do_upload($field_name))
			{
				//$error = array('error' => $this->upload->display_errors());
				$result['error'] = true;
				$result['message'] = $this->upload->display_errors();
				//$this->load->view('upload_form', $error);
			}	
			else
			{
				//$data = array('upload_data' => $this->upload->data());
				$result['error'] = false;
				$result['upload_data'] = $this->upload->data();
			}
			
			return $result;
		}	
		
		function view(){
			$this->load->library('pagination');
			
			$code_parent = $this->uri->segment(4);
			$_code_parent = $code_parent;
			$page = (int)$this->uri->segment(5);
			if($code_parent=='') $_code_parent = '_';
			$config['base_url'] = $this->base_url . 'admin/price/view/' . $_code_parent . '/';
						
			$config['total_rows'] = $this->files->countAll($code_parent);
			$config['per_page'] = NUMBER_RECORD_PER_PAGE;
			$config['uri_segment'] = 5;
			$config['first_link'] = 'First';
			
			$this->pagination->initialize($config);
			
			//$paging = $this->pagination->create_links();

			//$this->setTemplate(array ('admin/file/file_list.tpl'));
			//$items = $this->loadItems();
			//$items = '';
			$files = $this->files->getAll(NUMBER_RECORD_PER_PAGE, $page, $code_parent);
			/*$this->setTemplate(array ('admin/file/file_item.tpl'));
			for($i = 0; $i < count($files); $i++){
				$id = $files[$i]->id_file;
				$name = $files[$i]->vi_alias;
				$description = round(filesize($files[$i]->file_name)/1024/1024 , 3);  // MB
				$extend_name = end(explode('.', $files[$i]->file_name));
				$parent = '';//$pcategories[$i]->code;
				if($parent=='') $parent = '_';
				$enlable = $files[$i]->active == 1 ? 'checked.jpg' : 'nocheck.jpg';
				$items .= eval ($this->loadTemplate('admin/file/file_item.tpl'));
			}*/
			if($page > 0 AND count($files)==0){
				redirect('admin/price/view/' . ($page-NUMBER_RECORD_PER_PAGE));
				return;
			}
			$data = array();
			$data['rows'] = $files;
			$this->main = $this->load->view('admin/file/file_list', $data, true);
			//$this->main = eval ($this->loadTemplate('admin/file/file_list.tpl'));
			$this->execute();
		}
		
		function loadItems(){
			/*$item = '';
			$items = $this->pcategory->getAll();
			$this->setTemplate(array ('admin/pcategory/pcategory_item.tpl'));
			for($i = 0; $i < count($items); $i++){
				$id = $items[$i]->id_pcategory;
				$name = $items[$i]->vi_name;
				$description = $items[$i]->vi_description;
				$item .= eval ($this->loadTemplate('admin/pcategory/pcategory_item.tpl'));
			}
			
			return $item;*/
		}	
		
		
		function edit_news_category($id){
		
			$this->setTemplate('edit_news_category.tpl');
			$code = uniqid();
			$this->session->set_userdata('code', $code);
			$this->load->model('news_category_model', 'category', true);
			$category = $this->category->getById($id);
			
			if(!$category){
				redirect('category/view_news_category');
			}
			
			$txtID = $category->category_id;
			$txtNameVi = $category->name_vi;
			$txtNameEn = $category->name_en;
			$txtDescriptionVi = $category->description_vi;
			$txtDescriptionEn = $category->description_en;
			$cbActive = $category->active == 1 ? 'checked' : '';
			$error_message = '';
			$picture = $category->picture == "" ? "" : "<img src='".$this->base_url."data/categories/news/{$category->picture}' width=150 height=50";
			$category_parent = $this->buidDDProductCategoryList('ddlParentCategory', $category->category_parent_id);
			$content = eval($this->loadTemplate('edit_news_category.tpl'));
			$this->execute($content);
		}
		
		function view_news_category(){
		
			$this->load->model('news_category_model', 'category', true);
			$categories = $this->category->getAll();
			
			$this->setTemplate(array('news_categories.tpl', 'news_categories_item.tpl'));
			$items = $this->loadNewsItems($categories);
			$content = eval($this->loadTemplate('news_categories.tpl'));
			$this->execute($content);
		}
		
		function loadNewsItems($categories = null, $parent = 0, $track = array(), $style = 1, $index = 1){
			$items = '';
			if(!$categories){
				$categories = $this->category->getAll();
			}
			$tmp = array();
			for($i = 0; $i <count($categories); $i++){
				$category = $categories[$i];
				$tmp[$category->category_parent_id][$category->category_id] = $category;
			}
			
			
			if(isset($tmp[$parent])){
				$num_record = count($tmp[$parent]);
				foreach($tmp[$parent] as $k => $v){
					$parent = $v->category_id;
					$category_id = $v->category_id;
					$category_name = $v->name_vi;
					if($index%2 == 0) $class = 'class="bg"';
					else $class = '';
					$items .= eval($this->loadTemplate('news_categories_item.tpl'));
					//if(in_array($v->category_id, $track))
					$index++;
					$items .=$this->loadProductItems($categories , $parent, $track, $style + 1, $index);
				}
				
				/*for($j = 1; $j <= count($tmp[$parent]); $j++){
					if(isset($tmp[$parent][$j])){
						$category = $tmp[$parent][$j]; 
						$parent = $category->category_id;
						$category_id = $category->category_id;
						$category_name = $category->name;
						if($index%2 == 0) $class = 'class="bg"';
						else $class = '';
						$items .= eval($this->loadTemplate('product_categories_item.tpl'));
						//if(in_array($v->category_id, $track))
						$index++;
						$items .=$this->loadProductItems($categories , $parent, $track, $style + 1, $index);
					}
				}*/
			}
			//print_r($categories);
			return $items;
		}
		
		function view_product_category(){
			$this->load->model('product_category_model', 'category', true);
			$categories = $this->category->getAll();
			$items = $this->loadProductItems($categories);
			$content = eval($this->loadTemplate('product_categories.tpl'));
			$this->execute($content);
		}
		
		function loadProductItems($categories = null, $parent = 0, $track = array(), $style = 1, $index = 1){
			$items = '';
			if(!$categories){
				$categories = $this->category->getAll();
			}
			$tmp = array();
			for($i = 0; $i <count($categories); $i++){
				$category = $categories[$i];
				$tmp[$category->category_parent_id][$category->category_id] = $category;
			}
			
			
			if(isset($tmp[$parent])){
				$num_record = count($tmp[$parent]);
				foreach($tmp[$parent] as $k => $v){
					$parent = $v->category_id;
					$category_id = $v->category_id;
					$category_name = $v->name_vi;
					if($index%2 == 0) $class = 'class="bg"';
					else $class = '';
					$items .= eval($this->loadTemplate('product_categories_item.tpl'));
					//if(in_array($v->category_id, $track))
					$index++;
					$items .=$this->loadProductItems($categories , $parent, $track, $style + 1, $index);
				}
				
				/*for($j = 1; $j <= count($tmp[$parent]); $j++){
					if(isset($tmp[$parent][$j])){
						$category = $tmp[$parent][$j]; 
						$parent = $category->category_id;
						$category_id = $category->category_id;
						$category_name = $category->name;
						if($index%2 == 0) $class = 'class="bg"';
						else $class = '';
						$items .= eval($this->loadTemplate('product_categories_item.tpl'));
						//if(in_array($v->category_id, $track))
						$index++;
						$items .=$this->loadProductItems($categories , $parent, $track, $style + 1, $index);
					}
				}*/
			}
			//print_r($categories);
			return $items;
		}
		
		function buidDDProductCategoryList($name, $default){
			//$this->load->model('pcategory_model', 'category', true);
			$categories = $this->pcategory->getAll(); 
			$this->setTemplate(array('admin/option_ddl.tpl', 'admin/ddl.tpl'));
			$space = '';
			//$name = 'Parent';
			$value = '';
			$selected = '';
			$space= '';
			$label = 'Parent';
			$class = '';
			$action = '';
			$style = '';
			
			$tmp = array();
			for($i = 0; $i <count($categories); $i++){
				$category = $categories[$i];
				//$tmp[$category->id_parent_pcategory][$category->id_pcategory] = $category;
				$tmp[$category->code_parent][$category->code] = $category;
			}
			
			$options = eval($this->loadTemplate('admin/option_ddl.tpl')) . $this->getCategoryOption($tmp/*$categories*/, '', $default);
			return eval($this->loadTemplate('admin/ddl.tpl'));
		}
		
		function buidDDNewsCategoryList($name, $default){
			$this->load->model('news_category_model', 'category', true);
			$categories = $this->category->getAll();
			$this->setTemplate(array('admin/option_ddl.tpl', 'admin/ddl.tpl'));
			$space = '';
			$name = 'Parent';
			$value = 0;
			$selected = '';
			$options = eval($this->loadTemplate('admin/option_ddl.tpl')) . $this->getCategoryOption($categories, 0, $default);
			return eval($this->loadTemplate('admin/ddl.tpl'));
		}
		
		function getCategoryOption($tmp/*$categories*/, $parent = ''/*0*/, $default = ''/*0*/, $space = '&nbsp;'){
			$items = '';
			/*if(!$categories){
				$categories = $this->pcategory->getAll();
			}*/
			/*$tmp = array();
			for($i = 0; $i <count($categories); $i++){
				$category = $categories[$i];
				//$tmp[$category->id_parent_pcategory][$category->id_pcategory] = $category;
				$tmp[$category->code_parent][$category->code] = $category;
			}*/
			//print_r($tmp);		
			if(isset($tmp[$parent])){  
				$num_record = count($tmp[$parent]);
				foreach($tmp[$parent] as $k => $v){ 
					//$parent = $v->id_pcategory;
					//$value = $v->id_pcategory;
					//echo '<br>\n'.$parent . '_\n';
					$parent = $v->code;
					$value = $v->code;
					$label = $v->vi_name;
					$selected = '';
					if($value == $default) $selected = 'selected';
					$items .= eval($this->loadTemplate('admin/option_ddl.tpl'));
					
					$items .=$this->getCategoryOption($tmp/*$categories*/ , $parent, $default, $space . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
				}
			}
			
			return $items;
		}
			
		function save(){
			//$this->setTemplate('form_new_ncategory.tpl');
			$txtID = (int)trim($this->input->post('txtID'));
			$txtCode = trim($this->input->post('txtCode'));
						
			if($txtID > 0)
				$file = $this->files->getById($txtID);	
			else{
				$file = new stdClass();
				$file->id_file = 0;	
				$file->file_name = '';
				//$category->code_parent = '';	
			} 
			
			$this->load->helper(array('form', 'url'));
		
			$this->load->library('form_validation');
			$error_message = '';
			$attach_file = false;
			$file_upload = array('error'=> false);
			
			if($txtID == 0){
				$attach_file = true;
				$file_upload = $this->upload_file('file', './Data/Prices/');
				if($file_upload['error'])
					$error_message .=$file_upload['message'];
			}
			elseif(strlen($_FILES['file']['tmp_name'])>0 AND isset($_FILES['file']['tmp_name']) AND $txtID > 0){  //echo 'FILE name : '.$_FILES['file']['tmp_name'];
				$attach_file = true;
				$file_upload = $this->upload_file('file', './Data/Prices/');
				if($file_upload['error'])
					$error_message .=$file_upload['message'];
				
			}
			
		    //$this->form_validation->set_rules('parent', 'lang:parent_code', 'required|min_length[2]|max_length[120]');
			$this->form_validation->set_rules('txtViName', 'lang:vi_name', 'required|min_length[2]|max_length[120]');
			$this->form_validation->set_rules('txtEnName', 'lang:en_name', 'required|min_length[2]|max_length[120]');
			
			/*$this->form_validation->set_rules('password', 'Password', 'required');
			$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
			$this->form_validation->set_rules('email', 'Email', 'required');
			*/	
						
			if(!$file AND $txtID > 0){
				redirect('addmin/price/view');
				return;
			}
					
			//$category->code = trim($this->input->post('txtCode'));
			$file->vi_alias = trim($this->input->post('txtViName'));
			$file->en_alias = trim($this->input->post('txtEnName'));
			$file->description = trim($this->input->post('txtDescription'));
			
			$file->active = (int)$this->input->post('active');
			$file->id_category = (int)$this->input->post('category');
			$file->upd_date = date('Y-m-d H:i:s', time());
			//$error_message =''; // $this->loadErrorMessage('Thong diep loi.');
			//$category_parent = ''; //$this->buidDDNewsCategoryList('ddlParentCategory', 0);
			
			
			
			if ($this->form_validation->run() == FALSE OR ($attach_file == true AND $file_upload['error']==true)){
				//$code = uniqid();
				//$this->session->set_userdata('code', $code);
				if(!$file_upload['error'])
					@unlink('./Data/Prices/'.$file_upload['upload_data']['file_name']);
					
				$data = array();
				$data['file'] = $file;
				$data['ddlCategory'] = $this->buidDDProductCategoryList('category', $file->id_category);
				$data['error_message'] = '<div style="color:red">' . $error_message.validation_errors().'</div>';
				//if()
				$data['legend_text'] = $txtID>0 ?  lang('edit_information_file') : lang('upload_file');
				$this->main = $this->load->view('admin/file/create_file', $data, true);
				$this->execute();
				return;
			} 
			else{
				if($attach_file){
					if($txtID > 0 AND $file->file_name!='')
						@unlink($file->file_name);
						
					$file->file_name = './Data/Prices/'.$file_upload['upload_data']['file_name'];
				}
					
				$category = $this->pcategory->getByCode(trim($this->input->post('category')));
				$file->id_category = $category->id_pcategory;
				if($txtID > 0){
					
					$result = $this->files->update($file);
				}
				else{
					//$file->number_product = 0;
					//$file->level_depth = 0;
					$file->add_date = date('Y-m-d H:i:s', time());
					$result = $this->files->create($file);
					
				}
					
				redirect('admin/price/view');
			}
			
		}
		
		function code_check($code){ 
			$result = $this->pcategory->getByCode($code); 
			if ($result!=null){ 
				$this->form_validation->set_message('code_check', '%s is not available.');
				return FALSE;
			}
			else{
				return TRUE;
			}
		}
		
		function friendly_url_check($url){
			$result = $this->pcategory->getByLinkRewrite($url);
			if ($result!=null){ 
				$this->form_validation->set_message('friendly_url_check', '%s is not available.');
				return FALSE;
			}
			else{
				return TRUE;
			}
		}
		
		function testGetFile(){
 		$config = array(
 			'allowed' => array('JPEG', 'jpg', 'PNG', 'png', 'GIF', 'gif'),
 			'max_size'=> 1024000000 /*1Mb*/
 		);
 		
 		 $result = getFile($config, 'Data', 'http://images8.dantri.com.vn/ThumbImages/Uploaded/2009/05/08/lut080520094_327.jpg');
 		 
 		 if(!$result['error']) echo 'Get file success.';
 		 else echo $result['message'];
 		 
 	}
 	
 	function delete(){
 		$id = intval($this->uri->segment(4));
 		if($id>0)
 			$this->files->delete($id);
 		else{
 			if(($this->input->post('submitDelcategory'))){
 				$ids = $this->input->post('categoryBox');
 			 	if(count($ids))
 			 		$this->files->delete($ids);
 			}
 		}
 		redirect('admin/price');
 	}
 	
	}
?>
